app.controller("TreasuryHeaderController", ['$scope', '$rootScope', 'treasuryNavigationService', function ($scope, $rootScope, treasuryNavigationService) {
    $scope.submit = function () {
        if ($rootScope.submitAction) {
            $rootScope.submitAction();
        }
    }
    $scope.back = function () {
        if ($rootScope.backButtonAction)
            $rootScope.backButtonAction();
    }
    document.removeEventListener("NAVIGATION_BACK_EVENT");
    document.addEventListener("NAVIGATION_BACK_EVENT", function (evt) {
        if ($rootScope.backButtonAction)
            $rootScope.backButtonAction();
    }, false);
    $rootScope.pageTitle = "模拟考试";
}]);

app.controller("TreasuryHomeController", ['$location', '$scope', "$rootScope", "treasuryExamService", function ($location, $scope, $rootScope, treasuryExamService) {
    $rootScope.pageTitle = "驾考宝典";
    $scope.pageClass = "page-home";
    $rootScope.hasFooter = false;
    $rootScope.showBackButton = true;
    $rootScope.showSubmitButton = false;
    treasuryExamService.getExamList().then(function (data) {
        $scope.exams = data.subjects;
        return;
    });
    $scope.showExam = function (exam) {
        $rootScope.pageTitle = exam.title;
        $location.path(exam.action);
    }
    $rootScope.backButtonAction = function () {
        //WebViewJavascriptBridge.callHandler('exitUIWebView');
        if (window.WebViewJavascriptBridge) {
            WebViewJavascriptBridge.callHandler('exitUIWebView');
        } else if (browser.versions.android) {
            jsb.require('exitUIWebView', { "msg": "navigate back" }, function (response) {
                //Log.log(response);
            });
        }
    }
}]);

app.controller("TreasuryExamController", ['$location', '$scope', "$rootScope", "$routeParams", "$interval", "treasuryExamService",
    function ($location, $scope, $rootScope, $routeParams, $interval, treasuryExamService) {
        $scope.pageClass = "page-exam";
        $rootScope.showBackButton = true;
        $rootScope.showSubmitButton = false;
        $rootScope.questionsLoaded = false;

        $rootScope.backButtonAction = function () {
            $location.path("/treasury/submenu/" + $rootScope.curSubjectId);
        }

        $scope.exam = $rootScope.curExam;
        $scope.examResults = treasuryExamService.getExamResults($rootScope.examId);

        $rootScope.totalTimeout = $scope.exam.timeLimit * 60 + 1;
        $rootScope.timerTick = function () {
            $rootScope.totalTimeout--;
            $rootScope.remainTime = toTime($rootScope.totalTimeout);
        }

        $scope.mockExam = function () {
            $rootScope.timerTick();
            $rootScope.curExam = $scope.exam;
            $rootScope.curInterval = $interval($rootScope.timerTick, 1000);
            $rootScope.showTimer = true;
            $location.path("/treasury/question/0/type/2");
        };
        $scope.undoneFirst = function () {
            $rootScope.timerTick();
            $rootScope.curExam = $scope.exam;
            $rootScope.curInterval = $interval($rootScope.timerTick, 1000);
            $rootScope.showTimer = true;
            $location.path("/treasury/question/0/type/3");
        };

        $scope.showResult = function (index) {
            $location.path("/treasury/result/" + index);
        }
    }]);

toTime = function (seconds) {
    var min = Math.floor(seconds / 60);
    if (min < 10)
        min = "0" + min.toString();
    var sec = Math.floor(seconds % 60);
    if (sec < 10)
        sec = "0" + sec.toString();
    return min + ":" + sec;
}

app.controller("TreasuryQuestionController", ['$location', '$scope', "$rootScope", "$routeParams", "$interval", "treasuryExamService",
    function ($location, $scope, $rootScope, $routeParams, $interval, treasuryExamService) {
        $rootScope.gblFooterType = gblFooterType.treasuryQuestion;
        $rootScope.treasureHeader = true;

        $scope.pageClass = "page-question";
        var curQuestionId = $routeParams.questionId * 1;
        $scope.curQuestionId = curQuestionId + 1;
        $rootScope.examtype = $routeParams.type * 1;
        var curSectionId = $routeParams.sectionId * 1;
        $rootScope.curSectionId = curSectionId;

        switch ($rootScope.examtype) {
            case 1://错题
                $scope.isMock = false;
                $rootScope.showBackButton = true;
                break;
            case 2://全真模拟考
            case 3://错题优先
                $rootScope.showBackButton = false;
                $rootScope.showSubmitButton = true;
                $scope.isMock = true;
                $rootScope.submitAction = function () {
                    var today = new Date();
                    var dateString = today.getFullYear() + "-" + today.getMonth() + "-" + today.getDate();
                    var passedTime = $rootScope.curExam.timeLimit * 60 - $rootScope.totalTimeout;
                    var timeUsed = toTime(passedTime);
                    var score = $rootScope.examResult.correctId.length * 100 / $rootScope.curExam.mockCount;
                    var res = { date: dateString, timeUsed: timeUsed, score: score, isPassed: score >= 90 };
                    for (var i = 0; i < $rootScope.examResult.wrongId.length; i++) {
                        treasuryExamService.setError($rootScope.examId, $rootScope.examResult.wrongId[i]);
                    }

                    var id = treasuryExamService.addExamResult($rootScope.examId, res);
                    $interval.cancel($rootScope.curInterval);
                    $rootScope.showTimer = false;
                    $rootScope.treasureHeader = false;
                    $location.path("treasury/result/" + id);
                }
                break;
            case 4:// 章节练习
                $scope.isMock = false;
                $rootScope.showBackButton = true;
                treasuryExamService.setLastIndexForSection($rootScope.examId, curSectionId, curQuestionId);
                break;
            case 5:// 随机练习
                $scope.isMock = false;
                $rootScope.showBackButton = true;
                break;
            default:
                $scope.isMock = false;
                $rootScope.showBackButton = true;
                treasuryExamService.setLastIndex($rootScope.examId, curQuestionId);
                break;
        }

        if (!$rootScope.questionsLoaded) {
            $rootScope.questionsLoaded = true;
            $rootScope.examResult = Object();
            $rootScope.examResult.correctId = [];
            $rootScope.examResult.wrongId = [];
            switch ($rootScope.examtype) {
                case 1://错误
                    var errors = treasuryExamService.getErrors($rootScope.curExam.examId);
                    $rootScope.curQuestions = $rootScope.curExam.questions.filter(function (val) {
                        if (errors.indexOf(val.id * 1) > -1) {
                            if (curSectionId) {
                                return val.sectionId * 1 == curSectionId;
                            }
                            else {
                                return true;
                            }
                        }
                        return false;
                    });
                    $rootScope.pageTitle = $rootScope.curExam.errorTitle;
                    break;
                case 2://全真模拟考
                    $rootScope.pageTitle = $rootScope.curExam.title;
                    $rootScope.curQuestions = treasuryExamService.getMockQuestion($rootScope.curExam.questions, $rootScope.curExam.mockCount);
                    break;
                case 3://错题优先
                    $rootScope.pageTitle = $rootScope.curExam.title;
                    $rootScope.curQuestions = treasuryExamService.getUndoQuestions($rootScope.curExam.questions, $rootScope.curExam.mockCount, $rootScope.examId);
                    break;
                case 4:// 章节练习
                    $rootScope.pageTitle = $rootScope.curExam.chapterExamTitle;
                    $rootScope.curQuestions = treasuryExamService.getQuestionsBySection($rootScope.curExam.questions, curSectionId);
                    break;
                case 5:// 随机练习
                    $rootScope.pageTitle = $rootScope.curExam.randomExamTitle;
                    $rootScope.curQuestions = treasuryExamService.getMockQuestion($rootScope.curExam.questions, $rootScope.curExam.questions.length);
                    break;
                default://顺序练习
                    $rootScope.pageTitle = $rootScope.curExam.exercisetitle;
                    $rootScope.curQuestions = $rootScope.curExam.questions;
            }
        }

        $scope.question = $rootScope.curQuestions[curQuestionId];
        $scope.question.mutiple = $scope.question.answer.length > 1;
        $scope.question.selectedMutiAnswer = [];
        $scope.question.correctResult = toAnswer($scope.question.answer);

        $rootScope.currentIndex = (curQuestionId + 1) + "/" + $rootScope.curQuestions.length;
        $rootScope.curQuestionId = curQuestionId;
        $rootScope.hasFooter = true;
        $rootScope.showPrevButton = curQuestionId != 0;
        $rootScope.showNextButton = curQuestionId < $rootScope.curQuestions.length - 1;

        if (!$scope.question.status)
            $scope.question.status = [];

        $rootScope.prev = function () {
            if ($rootScope.curQuestionId > 0) {
                var path = "/treasury/question/" + ($rootScope.curQuestionId - 1);
                if ($rootScope.examtype) {
                    path += "/type/" + $rootScope.examtype;
                }
                if ($rootScope.curSectionId) {
                    path += "/section/" + $rootScope.curSectionId;
                }
                $location.path(path);
            }
        }
        $rootScope.next = function () {
            if ($rootScope.curQuestionId < $rootScope.curQuestions.length - 1) {
                var path = "/treasury/question/" + ($rootScope.curQuestionId + 1);
                if ($rootScope.examtype) {
                    path += "/type/" + $rootScope.examtype;
                }
                if ($rootScope.curSectionId) {
                    path += "/section/" + $rootScope.curSectionId;
                }
                $location.path(path);
            }
        }
        $rootScope.backButtonAction = function () {
            $interval.cancel($rootScope.curInterval);
            $rootScope.showTimer = false;
            $rootScope.treasureHeader = false;
            switch ($rootScope.examtype) {
                case 1://错题
                    $location.path("/treasury/error");
                    break;
                case 2://全真模拟考
                case 3://错题优先
                    $location.path("/treasury/exam");
                    break;
                case 4:// 章节练习
                    $location.path("/treasury/section");
                    break;
                default:
                    $location.path("/treasury/submenu/" + $rootScope.curSubjectId);
                    break;
            }
        }
        $scope.showOriginalImg = function () { //显示完整图片
            $scope.showMask = !$scope.showMask;
            event.stopPropagation();
        };
        $scope.selectOpetion = function (index) {

            if ($scope.question.answered)
                return;

            if ($scope.question.mutiple) {
                if ($scope.question.status[index] == 1) {
                    $scope.question.status[index] = 0;
                    $scope.question.selectedMutiAnswer[index] = 0;
                }
                else {
                    $scope.question.status[index] = 1;
                    $scope.question.selectedMutiAnswer[index] = index + 1;
                }
            }
            else {
                $scope.question.selectedAnswer = index + 1;
                $scope.question.status[index] = 1;
                $scope.answerChanged();
            }
        }

        $scope.answerChanged = function () {
            $scope.question.answered = true;

            if ($scope.question.mutiple) {
                var r = toAnswer($scope.question.selectedMutiAnswer);
                $scope.question.isCorrect = r == $scope.question.correctResult;
            }
            else {
                $scope.question.isCorrect = $scope.question.selectedAnswer == $scope.question.answer[0];
            }

            if ($scope.isMock) {
                if ($scope.question.isCorrect) {
                    var wrongIndex = $rootScope.examResult.wrongId.indexOf($scope.question.id);
                    if (wrongIndex > -1) {
                        $rootScope.examResult.wrongId.remove(wrongIndex);
                    }
                    $rootScope.examResult.correctId.push($scope.question.id);
                }
                else {
                    var rightIndex = $rootScope.examResult.correctId.indexOf($scope.question.id);
                    if (rightIndex > -1) {
                        $rootScope.examResult.correctId.remove(rightIndex);
                    }
                    $rootScope.examResult.wrongId.push($scope.question.id);
                }

                $rootScope.next();
            }
            else {
                for (var i = 0; i < $scope.question.answer.length; i++) {
                    var ca = $scope.question.answer[i] * 1 - 1;
                    $scope.question.status[ca] = 2;
                }

                for (var i = 0; i < $scope.question.status.length; i++) {
                    if ($scope.question.status[i] && $scope.question.status[i] == 1) {
                        $scope.question.status[i] = 3;
                    }
                }

                if ($scope.question.isCorrect) {
                    $rootScope.next();
                }
                else {
                    treasuryExamService.setError($rootScope.examId, $scope.question.id);
                }
            }
        }
    }]);

function toAnswer(array) {
    var result = "";
    if (array != null) {
        for (var i = 0; i < array.length; i++) {
            if (array[i] == undefined)
                continue;
            var r = "";
            switch (array[i] * 1) {
                case 1:
                    r = "A,";
                    break;
                case 2:
                    r = "B,";
                    break;
                case 3:
                    r = "C,";
                    break;
                case 4:
                    r = "D,";
                    break;
            }
            result += r;
        }
    }
    result = result.substring(0, result.length - 1);
    return result;
}

app.controller("TreasurySubmenuController", ['$location', '$scope', "$rootScope", "$routeParams", "$modal", "treasuryExamService", function ($location, $scope, $rootScope, $routeParams, $modal, treasuryExamService) {
    $rootScope.showBackButton = true;
    $rootScope.showSubmitButton = false;
    $rootScope.hasFooter = false;

    $scope.pageClass = "page-submenu";
    $rootScope.curSubjectId = $routeParams.subjectId * 1;
    var exam = "";
    if ($rootScope.curSubjectId == 1) {
        exam = "subject1";
        $rootScope.pageTitle = "科目一理论考试";
    }
    else if ($rootScope.curSubjectId == 2) {
        $rootScope.pageTitle = "科目二";
    }
    else if ($rootScope.curSubjectId == 3) {
        $rootScope.pageTitle = "科目三";
    }
    else if ($rootScope.curSubjectId == 4) {
        exam = "subject4";
        $rootScope.pageTitle = "科目四理论考试";
    }

    if (exam != "") {
        treasuryExamService.getExam(exam).then(function (data) {
            $scope.exam = data.exam;//驾考科目试题
            $rootScope.curExam = data.exam;
            $rootScope.examId = data.exam.examId;//驾考ID
            return;
        });

        $scope.showExam = function (index) {
            $rootScope.questionsLoaded = false;
            switch (index) {
                case 1://顺序练习
                    var questionId = treasuryExamService.getLastIndex($scope.exam.examId);
                    questionId = questionId < $scope.exam.questions.length ? questionId : 0;
                    $location.path("/treasury/question/" + questionId);
                    break;
                case 2://错题巩固
                    $location.path("/treasury/error");
                    break;
                case 3://模拟考试
                    $location.path("/treasury/exam");
                    break;
                case 4://章节练习
                    $location.path("/treasury/section");
                    break;
                case 5://随机练习
                    $location.path("/treasury/question/0/type/5");
                    break;
            }
        }
    }
    $rootScope.backButtonAction = function () {
        $location.path("/treasury");
    }
}]);

app.controller("TreasurySubitemController", ['$location', '$scope', "$rootScope", "$routeParams", "$modal", "treasurySubitemService", "treasuryExamService",
    function ($location, $scope, $rootScope, $routeParams, $modal, treasurySubitemService, treasuryExamService) {
        $rootScope.showBackButton = true;
        $rootScope.showSubmitButton = false;
        $rootScope.hasFooter = false;

        $scope.pageClass = "page-subitem";
        $rootScope.curSubjectId = $routeParams.subjectId * 1;
        var subject = "";
        var backUrl = '';
        if ($rootScope.curSubjectId == 2) {
            $rootScope.pageTitle = "科目二";
            backUrl = '/treasury/subitem/2'
            subject = "subject2";
        }
        else if ($rootScope.curSubjectId == 3) {
            $rootScope.pageTitle = "科目三";
            subject = "subject3";
            backUrl = '/treasury/subitem/3';
        }
        else {
            $rootScope.pageTitle = "详情";
        }

        $scope.pageClass = "page-home";
        treasurySubitemService.getSubject(subject).then(function (data) {
            $scope.subject = data.subject;
            return;
        });

        $scope.video = function (subjectId, id) {
            subjectId = subjectId.replace('subject', '');
            var queryParm = { "subjectType": subjectId, "itemId": id };
            treasuryExamService.getVideo(queryParm).then(function (data) {
                if (data.data != null && data.data.videoLink) {
                    $rootScope.videoLink = data.data.videoLink;
                    $location.path('/treasury/video').search({ backUrl: backUrl });
                }
                else {
                    var modalInstance = $modal.open({
                        templateUrl: 'views/treasury/tmpl_alert.html',
                        controller: AlertController,
                        size: 'sm',
                        resolve: {
                            obj: function () {
                                return { msg: '视频正在处理中' }
                            }
                        }
                    });
                }
            });
        }
        $scope.showDetail = function () {
            var modalInstance = $modal.open({
                templateUrl: 'views/treasury/tmpl_alert.html',
                controller: AlertController,
                size: 'sm',
                resolve: {
                    obj: function () {
                        return { msg: '此功能开发中' }
                    }
                }
            });
        }

        $rootScope.backButtonAction = function () {
            $location.path("/treasury");
        }
    }]);

app.controller("TreasurySectionController", ['$location', '$scope', "$rootScope", "$routeParams", "$interval", "treasuryExamService",
    function ($location, $scope, $rootScope, $routeParams, $interval, treasuryExamService) {
        $scope.pageClass = "page-exam";
        $rootScope.showBackButton = true;
        $rootScope.showSubmitButton = false;
        $rootScope.questionsLoaded = false;
        $rootScope.pageTitle = $rootScope.curExam.chapterExamTitle;
        $rootScope.backButtonAction = function () {
            $location.path("/treasury/submenu/" + $rootScope.curSubjectId);
        }

        treasuryExamService.getSectionList($rootScope.curExam.examId).then(function (data) {
            $scope.sections = data;
            for (var i = 0; i < $scope.sections.length; i++) {
                var section = $scope.sections[i];
                var questions = treasuryExamService.getQuestionsBySection($rootScope.curExam.questions, section.sectionId);
                $scope.sections[i].questionCount = questions.length;
            }
            return;
        });

        $scope.showExam = function (section) {
            var questionId = treasuryExamService.getLastIndexForSection($rootScope.curExam.examId, section.sectionId);
            questionId = questionId < $rootScope.curExam.questions.length ? questionId : 0;
            $location.path("/treasury/question/" + questionId + "/type/4/section/" + section.sectionId);
        };
    }]);

app.controller("TreasuryErrorController", ['$location', '$scope', "$rootScope", "$routeParams", "$modal", "$interval", "treasuryExamService",
    function ($location, $scope, $rootScope, $routeParams, $modal, $interval, treasuryExamService) {
        $scope.pageClass = "page-exam";
        $rootScope.showBackButton = true;
        $rootScope.showSubmitButton = false;
        $rootScope.questionsLoaded = false;
        $rootScope.pageTitle = $rootScope.curExam.errorTitle;
        $rootScope.backButtonAction = function () {
            $location.path("/treasury/submenu/" + $rootScope.curSubjectId);
        }

        var errors = treasuryExamService.getErrors($rootScope.curExam.examId);
        $scope.totalErrorCount = errors ? errors.length : 0;

        treasuryExamService.getSectionList($rootScope.curExam.examId).then(function (data) {
            $scope.sections = data;
            for (var i = 0; i < $scope.sections.length; i++) {
                var section = $scope.sections[i];
                if (errors) {
                    var errorCount = errors.filter(function (val) {
                        var question = treasuryExamService.getQuestionById($rootScope.curExam.questions, val);
                        if (question && question.sectionId == section.sectionId) {
                            return true;
                        }
                        else {
                            return false
                        }
                    });
                    $scope.sections[i].errorCount = errorCount.length;
                }
                else {
                    $scope.sections[i].errorCount = 0;
                }
            }
            return;
        });

        $scope.showExam = function (section) {
            if (section) {
                if (section.errorCount > 0) {
                    $location.path("/treasury/question/0/type/1/section/" + section.sectionId);
                }
                else {
                    var modalInstance = $modal.open({
                        templateUrl: 'views/treasury/tmpl_alert.html',
                        controller: AlertController,
                        size: 'sm',
                        resolve: {
                            obj: function () {
                                return { msg: '果然是高手，您没有任何错题' }
                            }
                        }
                    });
                }
            }
            else {
                if ($scope.totalErrorCount > 0) {
                    $location.path("/treasury/question/0/type/1");
                }
                else {
                    var modalInstance = $modal.open({
                        templateUrl: 'views/treasury/tmpl_alert.html',
                        controller: AlertController,
                        size: 'sm',
                        resolve: {
                            obj: function () {
                                return { msg: '果然是高手，您没有任何错题' }
                            }
                        }
                    });
                }
            }
        };

        $scope.clearErrors = function () {
            if ($scope.totalErrorCount > 0) {
                var modalInstance = $modal.open({
                    templateUrl: 'views/treasury/tmpl_alert_okcancel.html',
                    controller: OKCancelAlertController,
                    size: 'sm',
                    resolve: {
                        obj: function () {
                            return { msg: '确定要清空错题吗？' }
                        }
                    }
                });
                modalInstance.result.then(function (para) {
                    treasuryExamService.removeError($rootScope.curExam.examId);
                    $scope.totalErrorCount = 0;
                    for (var i = 0; i < $scope.sections.length; i++) {
                        $scope.sections[i].errorCount = 0;
                    }
                });
            }
            else {
                var modalInstance = $modal.open({
                    templateUrl: 'views/treasury/tmpl_alert.html',
                    controller: AlertController,
                    size: 'sm',
                    resolve: {
                        obj: function () {
                            return { msg: '您没有任何错题' }
                        }
                    }
                });
            }
        };
    }]);

app.controller("TreasuryResultController", ['$location', '$scope', "$rootScope", "$routeParams", "treasuryExamService", function ($location, $scope, $rootScope, $routeParams, treasuryExamService) {
    $rootScope.pageTitle = "考试成绩";
    $rootScope.hasFooter = false;
    $scope.pageClass = "page-result";
    $rootScope.showBackButton = true;
    $rootScope.showSubmitButton = false;
    var resId = $routeParams.resultId;

    $scope.result = treasuryExamService.getExamResult($rootScope.examId, resId);
    $rootScope.backButtonAction = function () {
        $location.path("/treasury/exam");
    }

    $scope.bgImage = $scope.result.isPassed ? "img_passed" : "img_failed";
}]);

var AlertController = function ($scope, $rootScope, $modalInstance, obj) {
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    }
    if (!obj) {
        obj = { msg: '此功能还在开发中' };
    }
    $scope.obj = obj;
}

var OKCancelAlertController = function ($scope, $rootScope, $modalInstance, obj) {
    $scope.ok = function () {
        $modalInstance.close('ok');
    }
    $scope.cancel = function () {
        $modalInstance.dismiss('cancel');
    }
    if (!obj) {
        obj = { msg: '此功能还在开发中' };
    }
    $scope.obj = obj;
}

app.controller("TreasuryVideoController", ['$scope', "$rootScope", function ($scope, $rootScope) {
    $scope.videoLink = $rootScope.videoLink;
}]);